package com.su.lightthings.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.telecom.TelecomManager
import android.telephony.TelephonyManager
import android.util.Log
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
//import com.android.internal.telephony.ITelephony
import com.su.lightthings.viewmodel.CommonViewModel
import java.lang.ref.WeakReference
import java.lang.reflect.Method

object CallUtil {
    private val TAG = "CallUtil"
    private var weakReference: WeakReference<AppCompatActivity>? = null

    fun setActivity(activity: AppCompatActivity) {
        weakReference = WeakReference(activity)
    }

    private fun getActivity(): AppCompatActivity? {
        return weakReference?.get()
    }

    fun control(type: Int) {
        val activity = getActivity()
        if (activity != null) {
            CommonViewModel.INSTANCE.doPermissionTask(Cons.LiveDataBus.PERMISSION_PHONE_INDEX, activity)
            when (type) {
                0 -> endCall(activity)
                2 -> answerCall(activity)
                else -> {}
            }
        }
    }

    /**
     * 接听电话
     */
    private fun answerCall(context: Context) {
        val telecomManager =
            context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ANSWER_PHONE_CALLS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        telecomManager.acceptRingingCall()
    }

    /**
     * 挂断电话
     */
    private fun endCall(context: Context): Boolean {
        var callSuccess = false
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val telecomManager =
                    context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager

                if (ActivityCompat.checkSelfPermission(
                        context, Manifest.permission.ANSWER_PHONE_CALLS
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    telecomManager.endCall()
                    callSuccess = true
                    Log.d(TAG, "挂断电话方法结束")
                } else {
                    Log.d(TAG, "没有权限")
                }
            } else {

                val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                val c = Class.forName(tm.javaClass.name)
                val m: Method = c.getDeclaredMethod("getITelephony")
                m.isAccessible = true
//                val telephonyService: ITelephony = m.invoke(tm) as ITelephony
//                callSuccess = telephonyService.endCall()
                Log.d(TAG, " telephonyService.endCall finish")
            }
        } catch (e: Exception) {
            Log.d(TAG, "Exception   error: " + e.message)
            callSuccess = disconnectCall()
            e.printStackTrace()
        }
        return callSuccess
    }

    private fun disconnectCall(): Boolean {
        try {
            Log.d(TAG, "input keyevent " + KeyEvent.KEYCODE_ENDCALL)
            Runtime.getRuntime().exec(
                "input keyevent " + KeyEvent.KEYCODE_ENDCALL.toString()
            ) //KEYCODE_HEADSETHOOK
        } catch (exc: Exception) {
            Log.d(TAG, "exc.printStackTrace")
            exc.printStackTrace()
            return false
        }
        return true
    }

}